package com.fudan.gamestore.controller;

import com.fudan.gamestore.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.*;

@Controller
public class ImageController {
    @Autowired
    private TokenService tokenService;

    @RequestMapping(value = "/gameImg/upload", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> imageUpload(MultipartFile[] files, HttpSession session, @RequestHeader String token) throws IOException {
        List<String> fileUrlList = new ArrayList<>();
        Map<String, Object> retMap = new HashMap<>();
        if(tokenService.checkToken(token, -1, 1) < 0){
            retMap.put("status", 400);
            retMap.put("info", "未授权");
            retMap.put("fileUrlList", fileUrlList);//此时为空
            return retMap;
        }

        // 获取ServletContext对象
        ServletContext servletContext = session.getServletContext();
        // 获取当前工程下photo目录的真实路径
        String imagePath = servletContext.getRealPath("static/images/");

        for (MultipartFile multiFile : files) {
            // 获取上传的文件的文件名
            String fileName = multiFile.getOriginalFilename();
            // 获取上传的文件的后缀名
            assert fileName != null;
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            // 获取uuid
            String uuid = UUID.randomUUID().toString();
            // 拼接一个新的文件名
            fileName = uuid + suffixName;
            //创建imagePath所对应的File对象
            File file = new File(imagePath);
            //判断file所对应目录是否存在
            if (!file.exists()) file.mkdir();
            // 构造实际路径
            String finalPath = imagePath + File.separator + fileName;
            // 写入文件
            multiFile.transferTo(new File(finalPath));
            // 保存fileName到到fileUrlList中
            fileUrlList.add(fileName);
        }

        retMap.put("status", 200);
        retMap.put("info", "success");
        retMap.put("fileUrlList", fileUrlList);
        return retMap;
    }
}
